<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
// import { sendMessageService } from '@/api/aiMessage'
import { useTokenStore } from '@/store/token.js';
import { MdPreview } from 'md-editor-v3'
import { useShowLoginDialogStore } from '@/store/showLoginDiaolg';

const tokenStore = useTokenStore()
const showLoginDialogStore = useShowLoginDialogStore()

// 对话列表对象
const messageListRef = ref(null)
// 用户输入内容
const userInput = ref('')
// 当前聊天总记录
const currentMessages = ref([])

// AI是否正在回答问题
const isStreaming = ref(false)

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messageListRef.value) {
    console.log("即将滚动")
    const container = document.getElementById('message-list')
    // console.log("document.getElementById('message-list')", container)
    // console.log("c.scrollTop", container.scrollTop)
    // console.log("c.scrollHeight", container.scrollHeight)
    // container.scrollTop = container.scrollHeight
    // messageListRef.value.scrollTop = messageListRef.value.scrollHeight

    // 滚动到最后一个元素
    const lastChild = container.lastElementChild;
    lastChild.scrollIntoView({ behavior: "smooth", block: "end" });
  }
}

// 发送消息函数
const sendMessage = async () => {
  // isStreaming为true，表明AI正在回答问题
  if (isStreaming.value) return
  if (!userInput.value.trim()) return

  console.log("准备发送消息")

  // 获取用户输入的内容 messageContent
  const messageContent = userInput.value.trim()

  // 添加用户消息
  const userMessage = { // 发送给后端的内容格式：
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  }
  currentMessages.value.push(userMessage)
  console.log("添加用户消息", currentMessages.value)

  // 清空用户输入
  userInput.value = ''
  await scrollToBottom()

  // 准备发送数据
  const formData = new FormData()
  formData.append('prompt', messageContent)

  // 添加助手消息占位
  const assistantMessage = {
    role: 'assistant',
    content: '',
    timestamp: new Date()
  }
  currentMessages.value.push(assistantMessage)

  // 开始发送消息给后端
  isStreaming.value = true
  try {
    // const reader = await sendMessageService(formData, currentChatId.value)
    // const reader = await sendMessageService(formData, 123)

    const url = new URL(`http://localhost:7070/user/ai/chat4Stream`)
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'token': tokenStore.token
      },
      body: formData,
    })

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let accumulatedContent = ''  // 添加累积内容变量
    while (true) {
      try {
        const { value, done } = await reader.read()
        if (done) break

        // 累积新内容
        accumulatedContent += decoder.decode(value)  // 追加新内容

        await nextTick(() => {
          // 更新消息，使用累积的内容
          const updatedMessage = {
            ...assistantMessage,
            content: accumulatedContent  // 使用累积的内容
          }
          const lastIndex = currentMessages.value.length - 1
          currentMessages.value.splice(lastIndex, 1, updatedMessage)
        })
        await scrollToBottom()
      } catch (readError) {
        console.error('读取流错误:', readError)
        break
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    isStreaming.value = false
    await scrollToBottom()
  }
}

// 加载特定对话的历史记录
const loadChat = async () => {
  try {
    console.log("store中存储的Token为", tokenStore.token)

    const response = await fetch(`http://localhost:7070/user/ai/getChatHistory`, {
      method: 'GET',
      headers: {
        'token': tokenStore.token
      },
      mode: 'cors'
    }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    const messages = await response.json()
    // 添加时间戳
    messages.map(msg => ({
      ...msg,
      timestamp: new Date() // 由于后端没有提供时间戳，这里临时使用当前时间
    }))

    currentMessages.value = messages
    console.log("加载特定对话的历史记录", currentMessages.value)
  } catch (error) {
    console.log("加载历史记录出错", error)
    currentMessages.value = []
    // 判断响应状态码，如果为401，则证明未登录，提示请登录，并显示登录框
    console.log('请先登录')
    // 显示登录框
    showLoginDialogStore.setShowLoginDialog(true)
  } finally {
    await scrollToBottom()
  }
}

onMounted(() => {
  // 加载特定对话
  loadChat()
})
</script>

<template>
  <div class="max-box">
    <div class="box-container">
      <div class="box-con">
        <!-- 1、标题 -->
        <div class="box-header">
          <div class="left">云舟 AI 助手</div>
          <div class="right">X</div>
        </div>
        <!-- 2、聊天内容区 -->
        <div class="box-chat">
          <div class="message-list" ref="messageListRef" id="message-list">
            <div v-for="item in currentMessages" class="list-item">
              <div v-if="item.role == 'user'" class="user-card">
                <div class="message">
                  <span>{{ item.content }}</span>
                </div>
              </div>
              <div v-else class="ai-card">
                <div class="message">
                  <!-- <span v-html="item.content"></span> -->
                  <MdPreview :modelValue="item.content"></MdPreview>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 3、输入框 -->
        <div class="box-input">
          <div class="main">
            <textarea class="text-input" placeholder="请输入相关问题..." v-model="userInput"></textarea>
            <div class="bottom">
              <button class="send-button" @click="sendMessage">Go</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.max-box {
  /* background-color: pink; */
  height: 650px;
  width: 500px;
}

.box-container {
  width: 100%;
  height: 100%;
  /* background-color: #f4f9ff; */
  background-color: #edf1f9;
  border-radius: 5px;
  padding: 12px 24px 8px;
}

.box-con {
  width: 100%;
  height: 100%;
  /* background-color: rgb(231, 223, 238); */
  position: relative;
}

/* 1、标题 */
.box-container .box-con .box-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  /* background-color: bisque; */
}

.box-container .box-con .box-header .left {
  cursor: default;
  font-weight: 600;
}

/* 2、聊天内容区 */
.box-container .box-con .box-chat {
  /* background-color: cornflowerblue; */
  overflow: auto;
  scrollbar-width: none;
  margin-bottom: 90px;
  /* 防止聊天内容区域超出我们的最大显示区域 */
  max-height: calc(100% - 140px);
}

.box-container .box-con .box-chat .message-list .list-item .user-card,
.box-container .box-con .box-chat .message-list .list-item .ai-card {
  margin-bottom: 20px;
  padding: 8px 12px;
  display: flex;
}

.box-container .box-con .box-chat .message-list .list-item .user-card {
  color: #fff;
  font-size: 13px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  justify-content: flex-end;
}

.box-container .box-con .box-chat .message-list .list-item .user-card .message {
  display: flex;
  background-color: #0082ff;
  padding: 8px 12px;
  border-radius: 12px 0 12px 12px;
}

.box-container .box-con .box-chat .message-list .list-item .ai-card {
  font-size: 13px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
}

.box-container .box-con .box-chat .message-list .list-item .ai-card .message {
  display: flex;
  background-color: #fff;
  padding: 8px 12px;
  border-radius: 0 12px 12px 12px;
}

/* 3、输入框 */
.box-container .box-con .box-input {
  /* background-color: azure; */
  width: 100%;
  position: absolute;
  bottom: 0;
  padding: 1px;
  border-radius: 8px;
  background: radial-gradient(circle at 0 0, rgba(83, 140, 255, .5), rgba(0, 102, 255, .5), rgba(123, 2, 197, .5), rgba(255, 125, 60, .5), rgba(255, 165, 60, .5));
}

.box-container .box-con .box-input .main {
  background-color: #fff;
  border-radius: 7px;
  padding: 10px;
}

.box-container .box-con .box-input .main .text-input {
  outline: none;
  border: none;
  font-size: 13px;
  width: 100%;
  height: 66px;
  resize: none;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  flood-color: #252933;
}

.box-container .box-con .box-input .main .bottom {
  text-align: end;
}

.box-container .box-con .box-input .main .bottom .send-button {
  border: none;
  cursor: pointer;
  background-color: #4d6bfe;
  color: #fff;
  height: 32px;
  width: 32px;
  border-radius: 5px;
}
</style>